﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class ClientsGroups : ClassManager.SessionManagerPage
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = "ClientGroupIdSource.Name";//GPSTrackingDBV2.Entities.ClientsGroupsColumn.Name.ToString();
                expression.SetSortOrder("Ascending");
                this.ClientsGrid.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected SessionManager getSessionManager()
        {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.showm_miniError", "objWindowsMessageManager.show_miniError('" + msg + "','Grupo Clientes...');", true);
        }

        public void showInfoMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniInfo", "objWindowsMessageManager.show_miniInfo('" + msg + "','Grupo Clientes...');", true);
        }

        public void showWarningMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_miniWarning", "objWindowsMessageManager.show_miniWarning('" + msg + "','Grupo Clientes...');", true);
        }

        protected void lbClearFilters_Click(object sender, EventArgs e)
        {
            ClientsGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in ClientsGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            ClientsGrid.MasterTableView.Rebind();
        }

        private void ResizeGrid()
        {
            decimal Height = Convert.ToDecimal(HiddenFieldHeight.Value);

            ClientsGrid.Height = Unit.Parse(Convert.ToString(Height));
        }

        private void GetGroupsByCompanyID()
        {
            SessionManager objSessionManager = new SessionManager();
            objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.ClientsGroupsByCompanies> ClientsGroupsByCompaniesEntity = GPSTrackingDBV2.Data.DataRepository.ClientsGroupsByCompaniesProvider.GetByCompanyId(objSessionManager.CompanyIDSelectedComboBox);
            GPSTrackingDBV2.Data.DataRepository.ClientsGroupsByCompaniesProvider.DeepLoad(ClientsGroupsByCompaniesEntity,true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.ClientsGroups));

            ClientsGrid.DataSource = ClientsGroupsByCompaniesEntity;
        }

        protected void ClientsGrid_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            GetGroupsByCompanyID();
            ResizeGrid();
        }

        private GPSTrackingDBV2.Entities.ClientsGroups Invoke_Entity(Hashtable Entity)
        {
            GPSTrackingDBV2.Entities.ClientsGroups ClientsGroupsEntity = new GPSTrackingDBV2.Entities.ClientsGroups();
            ClientsGroupsEntity.ClientGroupId = int.Parse(Entity["ClientGroupId"].ToString());
            ClientsGroupsEntity.Name = Entity["ClientGroupIdSource.Name"].ToString();

            return ClientsGroupsEntity;
        }

        protected void ClientsGrid_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {

                tm.BeginTransaction();

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                Entity["ClientGroupId"] = GPSTrackingDBV2Custom.Data.DataRepository.ClientsGroupsProvider.GetNextID();

                GPSTrackingDBV2.Entities.ClientsGroups ClientsGroupsEntity = Invoke_Entity(Entity);

                GPSTrackingDBV2.Data.DataRepository.ClientsGroupsProvider.Insert(tm, ClientsGroupsEntity);

                GPSTrackingDBV2.Entities.ClientsGroupsByCompanies ClientsGroupsByCompaniesEntity = new GPSTrackingDBV2.Entities.ClientsGroupsByCompanies();
                ClientsGroupsByCompaniesEntity.ClientGroupId = ClientsGroupsEntity.ClientGroupId;
                ClientsGroupsByCompaniesEntity.CompanyId = getSessionManager().CompanyIDSelectedComboBox;

                GPSTrackingDBV2.Data.DataRepository.ClientsGroupsByCompaniesProvider.Insert(tm, ClientsGroupsByCompaniesEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                showErrorMessage("No se puede registrar el grupo de clientes.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
            }
        }

        protected void ClientsGrid_UpdateCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();
                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.ClientsGroups ClientsGroupsEntity = Invoke_Entity(Entity);
                ClientsGroupsEntity.OriginalClientGroupId = int.Parse(Entity["ClientGroupId"].ToString());

                GPSTrackingDBV2.Data.DataRepository.ClientsGroupsProvider.Update(tm, ClientsGroupsEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                showErrorMessage("No se puede actualizar el grupo de clientes.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
            }
        }

        protected void ClientsGrid_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            GPSTrackingDBV2.Data.TransactionManager tm = GPSTrackingDBV2.Data.DataRepository.Provider.CreateTransaction();
            try
            {
                tm.BeginTransaction();

                GridEditableItem item = e.Item as GridEditableItem;
                Hashtable Entity = new Hashtable();
                item.ExtractValues(Entity);

                GPSTrackingDBV2.Entities.ClientsGroups ClientsGroupsEntity = Invoke_Entity(Entity);

                GPSTrackingDBV2.Data.DataRepository.ClientsGroupsByCompaniesProvider.Delete(getSessionManager().CompanyIDSelectedComboBox, ClientsGroupsEntity.ClientGroupId);

                GPSTrackingDBV2.Data.DataRepository.ClientsGroupsProvider.Delete(ClientsGroupsEntity);
                tm.Commit();
            }
            catch (Exception ex)
            {
                tm.Rollback();
                showErrorMessage("No se puede eliminar el grupo de clientes.");
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
            }
        }
    }
}